package com.dhcc.wb.interfaces;

import java.io.PrintWriter;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.json.JSONArray;
import org.json.JSONObject;

import com.dhcc.common.util.StringUtil;
import com.dhcc.wb.articleday.ArticleModel;
import com.dhcc.wb.articleday.ArticleTitleModel;
import com.dhcc.wb.articleday.ArticledayDao;
import com.dhcc.wb.gongzhonghao.GzhDao;
import com.dhcc.wb.gongzhonghao.GzhModel;
import com.dhcc.wb.gongzhonghao.UtilArticle2Model;
import com.dhcc.wb.gongzhonghao.UtilArticleModel;
import com.dhcc.wb.gongzhonghao.UtilGzhModel;
import com.dhcc.wb.qiye.QiyeDao;
import com.dhcc.wb.qiye.QiyeModel;
import com.dhcc.wb.user.UserDao;
import com.dhcc.wb.user.UtilUserModel;
import com.dhcc.wb.util.DateUtil;
import com.opensymphony.xwork2.ActionSupport;

public class UserInterfaceAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(UserInterfaceAction.class);
	
	private static final String JITUAN = "山西出版传媒集团有限责任公司";
	
	//企业数量
	public void interQiyeCount() throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = response.getWriter();
		JSONObject jsons = new JSONObject();
		QiyeDao dao = new QiyeDao();
		
		
		HttpServletRequest request = ServletActionContext.getRequest();
		String organName = request.getParameter("organName");
		
		if(StringUtil.isNullOrEmpty(organName)){
			organName = JITUAN;
			jsons.put("count", dao.queryCount(null));
		}else{
			if(JITUAN.equals(organName)){
				jsons.put("count", dao.queryCount(null));
			}else{
				jsons.put("count",1);
			}
		}
        out.println(jsons.toString());
	}
	//公众号数量
	public void interGzhCount() throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = response.getWriter();
		JSONObject jsons = new JSONObject();
		GzhDao dao = new GzhDao();
		
		HttpServletRequest request = ServletActionContext.getRequest();
		String organName = request.getParameter("organName");
		
		if(StringUtil.isNullOrEmpty(organName)){
			jsons.put("count", dao.queryCount(null));
		}else{
			if(JITUAN.equals(organName)){
				jsons.put("count", dao.queryCount(null));
			}else{
				jsons.put("count",dao.interGzhByqiyeNameCount(organName));
			}
		}
        out.println(jsons.toString());
	}
	
	//如果organName 为空，则查询所有的公众号
	public List<GzhModel> getgongzhonghao(String organName){
		GzhDao dao = new GzhDao();
		if(JITUAN.equals(organName)){
			organName = "";
		}
		return  dao.getGzhByqiyeNameCount(organName);
	}
	
	
	//昨天文章点击量
	public void interZuoTinaArticleCount() throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = response.getWriter();
		JSONObject jsons = new JSONObject();
		
		HttpServletRequest request = ServletActionContext.getRequest();
		String organName = request.getParameter("organName");
		
		String ref_date = request.getParameter("ref_date");
		if(StringUtil.isNullOrEmpty(ref_date)){
			ref_date = DateUtil.addDay(new Date(), -1);
		}
		List<GzhModel> gzhlist = getgongzhonghao(organName);
		
		ArticledayDao dao = new ArticledayDao();
		jsons.put("count", dao.queryCount2(ref_date,gzhlist));
        out.println(jsons.toString());
	}
	//数据走势图（没有用）
	public void interDataZouShiCount() throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = response.getWriter();
		JSONArray jsons = new JSONArray();
		JSONObject json;
		
		HttpServletRequest request = ServletActionContext.getRequest();
		String organName = request.getParameter("organName");
		List<GzhModel> gzhlist = getgongzhonghao(organName);
		
		ArticledayDao dao = new ArticledayDao();
		for(Integer i = -7;i<0;i++){//统计7天内
			json = new JSONObject();
			String date = DateUtil.addDay(new Date(), i);
			json.put(date,  dao.queryCount2(date,gzhlist));
			jsons.put(json);
		}
        out.println(jsons.toString());
	}
	//数据详情
	public void interDataCount() throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = response.getWriter();
		JSONArray jsons = new JSONArray();
		ArticledayDao dao = new ArticledayDao();
		
		HttpServletRequest request = ServletActionContext.getRequest();
		String organName = request.getParameter("organName");
		List<GzhModel> gzhlist = getgongzhonghao(organName);
		
		for(Integer i = -7;i<0;i++){//统计7天内
			JSONObject json = new JSONObject();
			String date = DateUtil.addDay(new Date(), i);
			json.put("ref_date", date);
			json.put("articleCount", dao.queryCount3(date,gzhlist));//文章数
			json.put("userCount", dao.queryCount4(date,gzhlist));//访问用户
			json.put("readCount", dao.queryCount2(date,gzhlist));//阅读次数
			jsons.put(json);
		}
        out.println(jsons.toString());
	}

	//根据企业name查公众号数量
	public void interGzhByqiyeCount() throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		PrintWriter out = response.getWriter();
		GzhDao dao = new GzhDao();
		JSONArray jsons = new JSONArray();
		
		HttpServletRequest request = ServletActionContext.getRequest();
		String organName = request.getParameter("organName");
		
		List<GzhModel> list = dao.fingByQiyeid(null);
		JSONObject json;
		
		QiyeDao qiyedao = new QiyeDao();
		
		if(list != null && list.size()>0){
			
			if(JITUAN.equals(organName)){
				for(GzhModel gzh : list){//
					
					
					QiyeModel qiye = qiyedao.queryqiyeByname_result(gzh.getQiyename());
					
						json = new JSONObject();
						json.put("qiyeid", qiye.getQiyeid());
						json.put("qiyename", gzh.getQiyename());//
						json.put("count",gzh.getExpire_in());//企业有的公众号
						jsons.put(json);
				}
			}else{
				for(GzhModel gzh : list){//
					if(gzh.getQiyename().equals(organName)){
						json = new JSONObject();
//						json.put("qiyeid", gzh.getQiyeid());
						json.put("qiyename", gzh.getQiyename());//
						json.put("count",gzh.getExpire_in());//企业有的公众号
						jsons.put(json);
					}
				}
			}
			
		}
		
        out.println(jsons.toString());
	}

	//企业拥有的公众号 的用户量
	public void interUserByQiyeOrGzh() throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		HttpServletRequest request = ServletActionContext.getRequest();
		String qiyeid = request.getParameter("qiyeid");
		String organName = request.getParameter("organName");
		
		PrintWriter out = response.getWriter();
		GzhDao gzhdao = new GzhDao();
		UserDao userdao = new UserDao();
		List<UtilGzhModel> result =new ArrayList<UtilGzhModel>();
		
		if(!StringUtil.isNullOrEmpty(qiyeid)){
			List<GzhModel> gzhlist = gzhdao.fingByQiyeid2(qiyeid);
			if(gzhlist != null && gzhlist.size()>0){
				for(GzhModel gzh : gzhlist){
					UtilGzhModel bean = new UtilGzhModel();
					bean.setGzhname(gzh.getGzhname());
					bean.setQiyename(gzh.getQiyename());
					Integer count = userdao.findMax(gzh.getGzhid());
					bean.setUsercount(count);
					bean.setQiyeid(gzh.getQiyeid());
					result.add(bean);
				}
				Collections.sort(result); // 排序
			}
		}else if(!StringUtil.isNullOrEmpty(organName)){
			List<GzhModel> gzhlist = gzhdao.fingByQiyeName((JITUAN.equals(organName))?null:organName);
			if(gzhlist != null && gzhlist.size()>0){
				for(GzhModel gzh : gzhlist){
					UtilGzhModel bean = new UtilGzhModel();
					bean.setGzhname(gzh.getGzhname());
					bean.setQiyename(gzh.getQiyename());
					Integer count = userdao.findMax(gzh.getGzhid());
					bean.setUsercount(count);
					bean.setQiyeid(gzh.getQiyeid());
					result.add(bean);
				}
				Collections.sort(result); // 排序
			}
		}
		
		JSONArray arr = new JSONArray(result);
        out.println(arr.toString());
	}
	
	
	
	//企业拥有的公众号的关注用户排行榜
	public void interUserByGzh() throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		
		HttpServletRequest request = ServletActionContext.getRequest();
		String organName = request.getParameter("organName");
		List<GzhModel> gzhlist = getgongzhonghao(organName);//获取所有的公众号
		
		
		PrintWriter out = response.getWriter();
		JSONArray jsons = new JSONArray();
		JSONObject json;
		UserDao userdao = new UserDao();
		List<UtilUserModel> list = userdao.interUserByGzh(gzhlist);
		
		Collections.sort(list); // 排序
		
		if(list != null && list.size()>0){
			for(UtilUserModel user : list){
				json = new JSONObject();
				json.put("gzhid",user.getGzhid());
				json.put("gzhname", user.getGzhname());//
				json.put("usercount", user.getCumulate_user());//企业有的公众号
				jsons.put(json);
			}
		}else{
			json = new JSONObject();
			json.put("gzhid","");
			json.put("gzhname","");//
			json.put("usercount", 0);//企业有的公众号
			jsons.put(json);
		}
		
        out.println(jsons.toString());
	}
	
	//用户总数
	public void interUserAll() throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		PrintWriter out = response.getWriter();
		UserDao userdao = new UserDao();
		
		
		HttpServletRequest request = ServletActionContext.getRequest();
		String organName = request.getParameter("organName");
		List<GzhModel> list = getgongzhonghao(organName);//获取所有的公众号 如果是集团，查询所有
		
		Integer sum = 0;
		if(list != null && list.size()>0){
			for(GzhModel gzh:list){
				sum += userdao.findMax(gzh.getGzhid());
			}
		}
		
		
//		List<GzhModel> list = gzhdao.getAll();
//		Integer sum = 0;
//		for(GzhModel gzh:list){
//			sum += userdao.findMax(gzh.getGzhid());
//		}
		JSONObject json = new JSONObject();
		json.put("userAllcount", sum);
        out.println(json.toString());
	}
	//今日新增
	public void interUserTodayNew() throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String  yestoday = DateUtil.addDay(new Date(), -1);
		PrintWriter out = response.getWriter();
		GzhDao gzhdao = new GzhDao();
		UserDao userdao = new UserDao();
		
		
		HttpServletRequest request = ServletActionContext.getRequest();
		String organName = request.getParameter("organName");
		List<GzhModel> list = getgongzhonghao(organName);//获取所有的公众号
		
//		List<GzhModel> list = gzhdao.getAll();
		Integer sum = 0;
		if(list != null && list.size()>0){
			for(GzhModel gzh:list){
				sum += userdao.findNew(gzh.getGzhid(), yestoday);
			}
		}
		
		JSONObject json = new JSONObject();
		json.put("userNewcount", sum);
        out.println(json.toString());
	}
	//今日取消
	public void interUserTodaycancal() throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String  yestoday = DateUtil.addDay(new Date(), -1);
		PrintWriter out = response.getWriter();
		GzhDao gzhdao = new GzhDao();
		UserDao userdao = new UserDao();
		
		HttpServletRequest request = ServletActionContext.getRequest();
		String organName = request.getParameter("organName");
		List<GzhModel> list = getgongzhonghao(organName);//获取所有的公众号
		
		
//		List<GzhModel> list = gzhdao.getAll();
		Integer sum = 0;
		
		if(list != null && list.size()>0){
			for(GzhModel gzh:list){
				sum += userdao.findCancal(gzh.getGzhid(), yestoday);
			}
		}
		
		
		JSONObject json = new JSONObject();
		json.put("userCancalcount", sum);
        out.println(json.toString());
	}

	
	//文章阅读排行
	public void interArticle() throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		HttpServletRequest request = ServletActionContext.getRequest();
		String ref_date = request.getParameter("ref_date");
		
		String organName = request.getParameter("organName");
		List<GzhModel> gzhlist = getgongzhonghao(organName);
		
		if(StringUtil.isNullOrEmpty(ref_date)){
			ref_date = DateUtil.addDay(new Date(), -1);
		}
		String[] arr = ref_date.split("-");
		PrintWriter out = response.getWriter();
		ArticledayDao articledaydao = new ArticledayDao();
		JSONObject json = new JSONObject();
		json.put("ref_date_format", arr[0]+"年"+arr[1]+"月"+arr[2]+"日");
		json.put("ref_date", ref_date);
		
		json.put("articleCount", articledaydao.queryCount2(ref_date,gzhlist));
		
//		title、阅读人数、公众号个数、阅读次数
		List<ArticleTitleModel> titlelist = articledaydao.findArticleDay(ref_date,gzhlist);
		
		List<UtilArticleModel> result =new ArrayList<UtilArticleModel>();
		if(titlelist != null && titlelist.size()>0){
			for(ArticleTitleModel article :titlelist){
				Integer usercount = articledaydao.findArticleDay1(ref_date, article.getTitle(),gzhlist);//阅读人数
				Integer gzhcount = articledaydao.findArticleDay2(ref_date, article.getTitle(),gzhlist);//公众号个数
				Integer readcount = articledaydao.findArticleDay3(ref_date, article.getTitle(),gzhlist);//阅读次数
				List<ArticleModel> list = articledaydao.findArticleDay5(ref_date, article.getTitle(),gzhlist);//推送此文章的公众号的名称list
				StringBuilder sb = new StringBuilder();
				for (int i = 0; i < list.size(); i++) {
					sb.append(list.get(i).getGzhname()).append("/");
				}
				UtilArticleModel model = new UtilArticleModel();
				model.setGzhcount(gzhcount);
				model.setReadcount(readcount);
				model.setTitle(article.getTitle());
				model.setUsercount(usercount);
				model.setGzhNameListToString(sb.toString().substring(0, sb.toString().length() - 1));
				result.add(model);
			}
			Collections.sort(result); // 排序
		}
		JSONArray jsonarr = new JSONArray(result);
		json.put("result", jsonarr);
        out.println(json.toString());
	}
		
		
	/**
	 * 文章阅读排行
	 * 入参：时间 文章title
	 * 返回：文章title,每个公众号的阅读人数、阅读数量
	 */
	public void interArticleSingle() throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		HttpServletRequest request = ServletActionContext.getRequest();
		String ref_date = request.getParameter("ref_date");
		String title = request.getParameter("title");
		
		String organName = request.getParameter("organName");
		List<GzhModel> gzhlist = getgongzhonghao(organName);
		
		if(StringUtil.isNullOrEmpty(ref_date)){
			ref_date = DateUtil.addDay(new Date(), -1);
		}
		if(StringUtil.isNullOrEmpty(title)){
			title = "";
		}
		
		String[] arr = ref_date.split("-");
		
		PrintWriter out = response.getWriter();
		ArticledayDao articledaydao = new ArticledayDao();
		JSONObject json = new JSONObject();
		json.put("ref_date", ref_date);
		json.put("ref_date_format", arr[0]+"年"+arr[1]+"月"+arr[2]+"日");
		json.put("title",title);
		List<ArticleModel> titlelist = articledaydao.findArticleDay4(ref_date,title,gzhlist);
        List<ArticleModel> list = articledaydao.findArticleDay5(ref_date, title,gzhlist);//推送此文章的公众号的名称list
        HashMap<String,List<ArticleModel>> map = new HashMap<String,List<ArticleModel>>();
		List<UtilArticle2Model> result =new ArrayList<UtilArticle2Model>();
        if ((list!=null&&list.size()!=0)&&(titlelist!=null&&titlelist.size()!=0)){
			//把每一个标题的公众号都按照‘标题’为key值列出来
			for (ArticleModel ar : list) {
				List<ArticleModel> t1 = new ArrayList<ArticleModel>();
				for (ArticleModel attt :titlelist) {
					if (ar.getGzhname().equals(attt.getGzhname())){
						t1.add(attt);
					}
				}
				map.put(ar.getGzhname(),t1);
			}
			HashMap<String,List<ArticleModel>> map1 = new HashMap<String,List<ArticleModel>>();
			//分解出每一个标题的公众号的list，list为1直接放在map1里，list大于1只把阅读量和阅读人数不等于0的放在map1里，
			for(Map.Entry<String,List<ArticleModel>> entry : map.entrySet()){
				List<ArticleModel> t3 = new ArrayList<ArticleModel>();
				String mapKey = entry.getKey();
				List<ArticleModel> t2 = entry.getValue();
				if (t2.size()==1){
					t3.addAll(t2);
				} else if (t2.size()>1){
					for (int i=0; i<t2.size();i++){
						if (t2.get(i).getInt_page_read_user()!=0&&t2.get(i).getInt_page_read_count()!=0){
							t3.add(t2.get(i));
						}
					}
					//如果公众号有多个但是阅读量和阅读人数都是0，那么就把第一个放在map1里
					if (t3.size()==0){
						t3.add(t2.get(0));
					}
				}
				map1.put(mapKey,t3);
			}
			for(Map.Entry<String,List<ArticleModel>> entry : map1.entrySet()){
				List<ArticleModel> t4 = entry.getValue();
				for(ArticleModel article :t4){
					UtilArticle2Model ent = new UtilArticle2Model();
					ent.setGzhid(article.getGzhid());
					ent.setGzhname(article.getGzhname());
					ent.setReadcount(article.getInt_page_read_count());
					ent.setUsercount(article.getInt_page_read_user());
					result.add(ent);
				}
			}
			Collections.sort(result); // 排序
			logger.info("所有数据拆分出来的map"+new Gson().toJson(map));
			logger.info("所有数据整合掉重复的数据的map1"+new Gson().toJson(map1));
		}
		JSONArray jsonarr = new JSONArray(result);
		json.put("result", jsonarr);
        out.println(json.toString());
//		List<UtilArticle2Model> result =new ArrayList<UtilArticle2Model>();
//		if(titlelist != null && titlelist.size()>0){
//			for(ArticleModel article :titlelist){
//				UtilArticle2Model ent = new UtilArticle2Model();
//				ent.setGzhid(article.getGzhid());
//				ent.setGzhname(article.getGzhname());
//				ent.setReadcount(article.getInt_page_read_count());
//				ent.setUsercount(article.getInt_page_read_user());
//				result.add(ent);
//			}
//			Collections.sort(result); // 排序
//		}
//		JSONArray jsonarr = new JSONArray(result);
//		json.put("result", jsonarr);
//        out.println(json.toString());
	}
			
		
		
		
		
		
		
	
	
}
